<script setup>
const SORT_LIST = ['', 'asc', 'desc']

const props = defineProps({
  // 对象形式为
  // {
  //   label: '排序',
  //   value: 'sort',
  //   type: 0, // 0 未选中 1 升序 2 降序
  // }
  sortList: {
    type: Array,
    default: () => [],
  },
  activeItem: {
    type: Object,
    default: () => ({}),
  },
})

const emits = defineEmits(['check'])

const _activeItem = ref({
  label: '',
  value: '',
  type: 0,
})
watch(
  () => props.activeItem,
  (val) => {
    console.log('activeItem', val)
    _activeItem.value = val
  },
  { immediate: true },
)

const _sortList = ref([])
watch(
  () => props.sortList,
  (val) => {
    console.log('sortList', val)
    _sortList.value = val
  },
  { immediate: true },
)

const checkSort = (item) => {
  console.log('item', item)
  console.log('_activeItem.value', _activeItem.value)
  if (_activeItem.value.value === item.value) {
    _activeItem.value.type = (_activeItem.value.type + 1) % 3
  } else {
    // 先将所有排序类型设为 0
    _sortList.value.forEach((item) => {
      item.type = 0
    })
    _activeItem.value = item
    _activeItem.value.type = 1
  }
  emits('check', {
    ..._activeItem.value,
    sortType: SORT_LIST[_activeItem.value.type],
  })
}
</script>

<template>
  <view class="sort-bar">
    <view
      v-for="item in _sortList"
      :key="item.value"
      class="sort-bar-item"
      :class="{ active: _activeItem.value === item.value }"
      @click="checkSort(item)"
    >
      <view class="sort-bar-item-text">{{ item.label }}</view>
      <template>
        <image
          v-if="item.type === 0"
          class="h-32rpx w-32rpx"
          src="/static/icons/sort-no.png"
        />
        <image
          v-if="item.type === 1"
          class="h-32rpx w-32rpx"
          src="/static/icons/sort-asc.png"
        />
        <image
          v-if="item.type === 2"
          class="h-32rpx w-32rpx"
          src="/static/icons/sort-desc.png"
        />
      </template>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.sort-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  border-radius: 16rpx;

  &-item {
    position: relative;
    display: flex;
    flex: 1;
    align-items: center;
    justify-content: center;
    height: 80rpx;

    &::after {
      position: absolute;
      top: 50%;
      right: 0;
      width: 1rpx;
      height: 32rpx;
      content: '';
      background-color: #eee;
      transform: translateY(-50%);
    }

    &:last-child {
      &::after {
        display: none;
      }
    }

    &-text {
      margin-right: 4rpx;
      font-size: 28rpx;
      color: $uni-text-color;

      &.active {
        color: #f98f18;
      }
    }
  }
}
</style>
